﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


//负责在每一关开始时，随机选择若干图片格子作为本关需要点击的目标，并控制这些格子的激活、重置、动画等。
public class PickRandom : MonoBehaviour
{
    //游戏的背景
    public GameObject groupObject;

    public SetUp setUp;
    public bool canClick = false;


    //？？
    private int[] z = new int[100];

    //得到可以翻转的格子
    private GameObject[] Pics
    {
        get
        {
            return GameObject.FindGameObjectsWithTag("FocusGameObject");
        }
    }

    private RectTransform rt;
    private Vector3 leaveStartPoint;
    private Vector3 leaveEndPoint;
    private Vector3 comeBackStartPoint;
    private Vector3 comeBackEndPoint;

    public UIManager uiManager;

    private void OnEnable()
    {
        CheckHit.LevelCompleted += OnLevelCompleted;
    }

    private void OnDisable()
    {
        CheckHit.LevelCompleted -= OnLevelCompleted;
    }

    void Start()
    {
        leaveStartPoint = groupObject.GetComponent<RectTransform>().localPosition;
        comeBackEndPoint = groupObject.GetComponent<RectTransform>().localPosition;
        leaveEndPoint = new Vector3(1000, groupObject.GetComponent<RectTransform>().localPosition.y, 0);
        comeBackStartPoint = new Vector3(-1368, groupObject.GetComponent<RectTransform>().localPosition.y, 0);
        rt = groupObject.GetComponent<RectTransform>();
    }

    public void Init()
    {
        this.setUp.Init();
        Invoke(nameof(RandomAppear), GameManager.Instance.appearAfter);
    }

    #region 将所有格子右移
    IEnumerator CRMoveGridRight(float moveTime)
    {
        

        float startTime = Time.time;
        //print(moveTime);
        //while (Time.time - startTime < moveTime)
        //{
        //    float f = (Time.time - startTime) / moveTime;
        //    print(rt.localPosition + "..." + leaveStartPoint + "..." + leaveEndPoint + "..." + f);
        //    rt.localPosition = Vector3.Lerp(leaveStartPoint, leaveEndPoint, f);
        //    yield return null;
        //}
        //rt.localPosition = leaveEndPoint;
        //startTime = Time.time;
        //while (Time.time - startTime < moveTime)
        //{
        //    float f = (Time.time - startTime) / moveTime;
        //    rt.localPosition = Vector3.Lerp(comeBackStartPoint, comeBackEndPoint, f);
        //    yield return null;
        //}
        //print("右移");
        yield return null;
        rt.localPosition = comeBackEndPoint;
        Invoke(nameof(RandomAppear), GameManager.Instance.appearAfter);
        //if (GameManager.Instance.showRemainedTilesCount)
        //    uiManager.countText.gameObject.SetActive(true);
    }
    #endregion

    public void ReSetGridType(float moveTime)
    {
        rt.localPosition = comeBackEndPoint;
        Invoke(nameof(RandomAppear), GameManager.Instance.appearAfter);
        //if (GameManager.Instance.showRemainedTilesCount)
        //    uiManager.countText.gameObject.SetActive(true);
    }

    /// <summary>
    /// 执行格子右移的函数
    /// </summary>
    public void OnLevelCompleted()
    {
        StartCoroutine(CRMoveGridRight(GameManager.Instance.disappearTime / 2));
        GameManager.Instance.ResetGameOpenedSpriteManger();
    }


    //// 重置所有格子
    //public void ResetBack()
    //{
    //    for (int p = 0; p < setUp.numberOfPreviousPics; p++)
    //    {
    //        //将脚本设置为不可用？
    //        Pics[p].GetComponent<ChangePic>().enabled = false;
    //        //初始化
    //        Image img = Pics[p].GetComponent<Image>();
    //        img.sprite = GameManager.Instance.defaultSprite;
    //        Pics[p].GetComponent<ChangePic>().CanChange = false;
    //        Pics[p].GetComponent<ChangePic>().isHit = false;
    //    }
    //}

    public void ResetBack()
    {
        
        // 遍历前 numberOfPreviousPics 个;格子（假设 PICS 数组已正确初始化）
        for (int p = 0; p < setUp.numberOfPreviousPics; p++)
        {
            // 1. 禁用 ChangePic 组件（可能用于停止状态变更逻辑）
            Pics[p].GetComponent<ChangePic>().enabled = false;

            // 2. 获取 Image 组件并设置为默认精灵（恢复初始显示）
            Image img = Pics[p].GetComponent<Image>();
            img.sprite = GameManager.Instance.defaultSprite;

            // 3. 重置 ChangePic 组件的状态标记
            Pics[p].GetComponent<ChangePic>().CanChange = false; // 禁止变化
            Pics[p].GetComponent<ChangePic>().isHit = false;     // 清除命中标记
        }
    }
    // 随机设置可翻转的牌
    void RandomAppear()
    {

        z[0] = Random.Range(0, setUp.numberOfPics);
        for (int j = 1; j < gameObject.GetComponent<CheckHit>().numberOfHit; j++)
        {
            for (int k = 0; k < 100; k++)
            {
                int t = -1;
                z[j] = Random.Range(0, setUp.numberOfPics);
                for (int l = 0; l < j; l++)
                {
                    t++;
                    if (z[l] == z[j])
                        break;
                }
                if (z[t] != z[j])
                    break;
            }

        }

        for (int k = 0; k < setUp.numberOfPics; k++)
        {
            for (int i = 0; i <= gameObject.GetComponent<CheckHit>().numberOfHit; i++)
            {
                if (i == gameObject.GetComponent<CheckHit>().numberOfHit)
                {
                    Pics[k].GetComponent<ChangePic>().enabled = false;
                    Pics[k].GetComponent<ChangePic>().CanChange = false;
                    break;
                }
                else if (k == z[i])
                {
                    Pics[k].GetComponent<ChangePic>().enabled = true;
                    Pics[k].GetComponent<ChangePic>().CanChange = true;
                    break;
                }
            }
        }

        // 延长几秒允许点击
        Invoke("SetCanClickTrue", GameManager.Instance.changePicAfter + 0.1f);
    }

    void SetCanClickTrue()
    {
        canClick = true;
    }

}
